package com.nan.controller;

import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Set;



@Slf4j
@Controller
@RequestMapping("/ptj")
public class ParamToJSONController {

    /* 获取条码 */
    @PostMapping("/getProductSnByEquipmentSn")
    @ResponseBody
    public String getProductSnByEquipmentSn(@RequestParam String MESurl, @RequestParam String Fixture){
//        String MESurl = "http://10.109.190.42:311/api/EquipmentAndProduct/getProductSnByEquipmentSn";
        JSONObject json = new JSONObject();
        json.put("Fixture", Fixture);
        System.out.println(json.toString());
        return forward(MESurl,json.toString());
    }

    /* CR080 组装校验接口 */
    @PostMapping("/processPlan")
    @ResponseBody
    public String processPlan(@RequestParam String MESurl,
                              @RequestParam(required = false, defaultValue = "") String ip,
                              @RequestParam(required = false, defaultValue = "") String workPlace,
                              @RequestParam(required = false, defaultValue = "") String line,
                              @RequestParam(required = false, defaultValue = "") String operation,
                              @RequestParam(required = false, defaultValue = "") String workOrderCode,
                              @RequestParam(required = false, defaultValue = "") String user,
                              @RequestParam(required = false, defaultValue = "") String dateTime,
                              @RequestParam(required = false, defaultValue = "") String sn,
                              @RequestParam(required = false, defaultValue = "") String componentSn,
                              @RequestParam(required = false, defaultValue = "") String slot,
                              @RequestParam(required = false, defaultValue = "") String holber,
                              @RequestParam(required = false, defaultValue = "") String cover,
                              @RequestParam(required = false, defaultValue = "") String carrier
    ){
//        String MESurl = "http://10.109.190.42:311/api/Product/processCheck/processPlan";
        JSONObject json = new JSONObject();
        json.put("ip", ip);
        json.put("workPlace", workPlace);
        json.put("line", line);
        json.put("operation", operation);
        json.put("workOrderCode", workOrderCode);
        json.put("user", user);
        json.put("dateTime", dateTime);
        json.put("sn", sn);
        json.put("componentSn", componentSn);
        json.put("slot", slot);
        json.put("holber", holber);
        json.put("cover", cover);
        json.put("carrier", carrier);
        System.out.println(json.toString());
        return "{\n" +
                "    \"state\": false,\n" +
                "    \"description\": \"string\"\n" +
                "}\n";
//        return forward(MESurl,json.toString());
    }

    /* CR080 组装过站*/
    @PostMapping("/assemblyPassWorkPlace")
    @ResponseBody
    public String assemblyPassWorkPlace(@RequestParam String MESurl,
                                        @RequestParam(required = false, defaultValue = "") String ip,
                                        @RequestParam(required = false, defaultValue = "") String workPlace,
                                        @RequestParam(required = false, defaultValue = "") String line,
                                        @RequestParam(required = false, defaultValue = "") String operation,
                                        @RequestParam(required = false, defaultValue = "") String workOrderCode,
                                        @RequestParam(required = false, defaultValue = "") String sn,
                                        @RequestParam(required = false, defaultValue = "") String user,
                                        @RequestParam(required = false, defaultValue = "") String slot,
                                        @RequestParam(required = false, defaultValue = "") String holber,
                                        @RequestParam(required = false, defaultValue = "") String cover,
                                        @RequestParam(required = false, defaultValue = "") String carrier,
                                        @RequestParam(required = false, defaultValue = "") String dateTime,
                                        @RequestParam(required = false, defaultValue = "") String components
    ){
//        String MESurl = "http://10.109.190.42:311/api/Product/processCheck/processPlan";
        JSONObject json = new JSONObject();
        json.put("ip", ip);
        json.put("workPlace", workPlace);
        json.put("line", line);
        json.put("operation", operation);
        json.put("workOrderCode", workOrderCode);
        json.put("user", user);
        json.put("dateTime", dateTime);
        json.put("sn", sn);
        json.put("components", components);//这个是数组，要确认一下怎么传
        json.put("slot", slot);
        json.put("holber", holber);
        json.put("cover", cover);
        json.put("carrier", carrier);
        System.out.println(json.toString());
        return forward(MESurl,json.toString());
    }

    /* CHECKIN流程检查 */
    //需要确认参数名字大小写
    @PostMapping("/checkIn")
    @ResponseBody
    public String checkIn(@RequestParam String MESurl,
                          @RequestParam(required = false, defaultValue = "") String ip,
                          @RequestParam(required = false, defaultValue = "") String workPlace,
                          @RequestParam(required = false, defaultValue = "") String Line,
                          @RequestParam(required = false, defaultValue = "") String Operation,
                          @RequestParam(required = false, defaultValue = "") String user,
                          @RequestParam(required = false, defaultValue = "") String dateTime,
                          @RequestParam(required = false, defaultValue = "") String Sn,
                          @RequestParam(required = false, defaultValue = "") String Slot,
                          @RequestParam(required = false, defaultValue = "") String holber,
                          @RequestParam(required = false, defaultValue = "") String cover,
                          @RequestParam(required = false, defaultValue = "") String carrier
    ){
//        String MESurl = "http://10.109.190.42:311/api/Product/processCheck/processPlan";
        JSONObject json = new JSONObject();
        json.put("ip", ip);
        json.put("workPlace", workPlace);
        json.put("Line", Line);
        json.put("operation", Operation);
        json.put("user", user);
        json.put("dateTime", dateTime);
        json.put("Sn", Sn);
        json.put("Slot", Slot);
        json.put("holber", holber);
        json.put("cover", cover);
        json.put("carrier", carrier);
        System.out.println(json.toString());
        return forward(MESurl,json.toString());
    }


    @GetMapping("/id")
    @ResponseBody
    public String id(){
//        String forward = forward("http://localhost:8081/ptj/test", "\"Fixture\": \"CR-02-AUTO-0574\"");
        System.out.println("forward");
        log.info("forward");
        return "success";
    }


    /* 接受请求获取参数 */
    @PostMapping
    @ResponseBody
    public String test(@RequestParam MultiValueMap<String, String> allParams){
        String url = "";
        JSONObject json = new JSONObject();
        Set<String> keys = allParams.keySet();
        for (String key : keys) {
            String value = this.removeFirstLastChar(allParams.get(key).toString(), 1);
            if ("MESurl".equals(key)){
                url = value;
            }else {
//              System.out.println(value);
                if (value.matches("\\{\\[([A-Z0-9]+(,[A-Z0-9]+)*)\\]\\}")) {
                    String tempValue = this.removeFirstLastChar(value, 2);
                    String[] split = tempValue.split(",");
                    // 创建一个新的 JSON 数组
                    org.json.JSONArray jsonArray = new org.json.JSONArray();
                    for (String item : split) {
                        JSONObject itemJson = new JSONObject();
                        itemJson.put("sn", item);
                        jsonArray.put(itemJson);
                    }
                    value = jsonArray.toString();
                }
                json.put(key, value);
            }
        }
        log.info("url:{}", url,";json:{}",json.toString());
        return this.forward(url,json.toString());
    }

    /* 删除首位字符 */
    public String removeFirstLastChar(String str,int i){
        return str.substring(i,str.length()-i);
    }

    /*请求EMS*/
    public String forward(String requestUrl,String param){
        String res = "";
        try {
        // 创建URL对象
        URL url = new URL(requestUrl);

        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为POST
        connection.setRequestMethod("POST");

        // 设置请求头Content-Type为application/json
        connection.setRequestProperty("Content-Type", "application/json; utf-8");

        // 允许输出（默认情况下不允许）
        connection.setDoOutput(true);

        // JSON请求体数据
        String jsonInputString = param; // 直接使用param参数

        // 发送请求体
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 获取响应状态码
        int responseCode = connection.getResponseCode();
        System.out.println("Response Code : " + responseCode);
        // 读取响应内容
        if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                // 打印响应内容
//                System.out.println("Response: " + response.toString());
                log.info("Response: {}", response.toString());
                res = response.toString();
            }
        } else {
            log.warn("GET request did not work. Response Code: " + responseCode);
            System.out.println("GET request did not work. Response Code: " + responseCode);
        }
        // 关闭连接
        connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
}
